package com.febs.web.controller;

import com.febs.common.domain.FebsConstant;
import com.febs.common.utils.FebsUtil;
import com.febs.security.helper.FebsJwtTokenHelper;
import com.febs.system.service.RoleService;

import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import lombok.RequiredArgsConstructor;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/6/21
 */
@RequiredArgsConstructor
@Controller
public class ViewController {

    private final FebsJwtTokenHelper tokenHelper;
    private final RoleService roleService;

    @GetMapping("login")
    @ResponseBody
    public ModelAndView login(HttpServletRequest request) {
        if (FebsUtil.isAjaxRequest(request)) {
            throw new SessionAuthenticationException("session过期");
        } else {
            ModelAndView mav = new ModelAndView();
            mav.setViewName(FebsUtil.view("login"));
            return mav;
        }
    }

    @GetMapping("/")
    public String redirectIndex() {
        return "redirect:/index";
    }

    @GetMapping("index")
    public String index(Model model) {
        /*FebsLoginUser loginUser = Optional.ofNullable(tokenHelper.getLoginUserFromToken(HttpContextUtils.getRequest()))
                .orElse(tokenHelper.getLoginUserFromUuid(HttpContextUtils.getRequest().getParameter(FebsConstant.LOGIN_USER_KEY)));
        if (ObjectUtil.isEmpty(loginUser)) {
            return "redirect:login";
        }
        loginUser.setPassword("It's a secret");
        model.addAttribute("user", loginUser);
        model.addAttribute("permissions", loginUser.getPermissions());
        List<String> roles = roleService.findUserRole(loginUser.getUsername()).stream().map(Role::getRoleName).collect(Collectors.toList());
        model.addAttribute("roles", roles);*/
        return "index";
    }

    @RequestMapping(FebsConstant.VIEW_PREFIX + "index")
    public String pageIndex() {
        return FebsUtil.view("index");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "layout")
    public String layout() {
        return FebsUtil.view("layout");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "404")
    public String error404() {
        return FebsUtil.view("error/404");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "403")
    public String error403() {
        return FebsUtil.view("error/403");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "500")
    public String error500() {
        return FebsUtil.view("error/500");
    }
}
